package com.mantou.proxyadapter.importer;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mantou.proxyadapter.net.HttpClientDownloader;
import com.mantou.proxyadapter.pool.Proxy;

public class DefaultImporter implements Importer {

	private static int pagenow =1;
	private static int pagesize =100;
	@Override
	public List<Proxy> newproxy(int number) {
		// TODO Auto-generated method stub

		List<Proxy> ret = new ArrayList<Proxy>();
		if(number<=0){
			return ret;
		}
		HttpClientDownloader downloader = new HttpClientDownloader();

		int failedtime =0;

		while(ret.size() <number){
			String json = downloader.download("http://123.56.155.209/proxyservice/proxy/query/"+pagenow+++"/"+pagesize,1);
			if(json == null){
				failedtime++;
				continue;
			}
			
			failedtime =0;
			JSONArray jsonarray = JSONArray.parseArray(json);
			Iterator<Object> iterator = jsonarray.iterator();
			if(jsonarray.size() <=0){
				failedtime ++;
				continue;
			}
			if(failedtime>=3)
				return ret;
			while(iterator.hasNext()){
				JSONObject obj = JSONObject.parseObject(iterator.next().toString());
				String ip = obj.getString("ip");
				Integer port = obj.getInteger("port");
				if(ip != null && port != null){
					ret.add(new Proxy(ip, port));
				}
				//Proxy proxy = new Proxy();
			}
		}
		return ret;
	}

}
